package com.erp.erp_ui.Inquiry;

import com.alibaba.fastjson.JSONObject;
import com.erp.erp_entitys.Inquiry.*;
import com.erp.erp_entitys.Inquiry.req.inquiryStatisticsReq;
import com.erp.erp_entitys.User.UserEntity;
import com.erp.erp_servers.Ftp.IFtpService;
import com.erp.erp_servers.Inquiry.*;
import com.erp.erp_ui.base.Base;
import com.erp.utils.DateUtils;
import com.erp.utils.R;
import com.erp.utils.ResultStatusEnum;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "inquiry")
@Api( tags = "询盘登记")
@Slf4j
public class InquiryControl extends Base {
    @Autowired
    private IInquiryService inquiryService;
    @Autowired
    private IInquiryProductService inquiryProductService;
    @Autowired
    private IInquiryFileService inquiryFileService;
    @Autowired
    private IInquiryRecordService inquiryRecordService;
    @Autowired
    private IFtpService ftpService;
    

    /**
     * 新增询盘登记
     * @param inquiry
     * @return 操作记录数
     */
    @RequestMapping(value = "insert" ,method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "新增询盘登记", notes = "新增询盘登记", httpMethod = "POST")
    public R<Integer> insert(@RequestBody InquiryEntity inquiry){
        try {
            Object cacheUser = this.getBean("user");
            if (null!=cacheUser){
                if(StringUtils.isEmpty(inquiry.getOddNumber())){
                    return  R.buildError(ResultStatusEnum.NOT_EMPTY);
                }
                boolean isExist = inquiryService.isExist(inquiry.getOddNumber());
                if(isExist){
                    return  R.buildError(ResultStatusEnum.BILL_NO_REPEAT);
                }
                UserEntity user = (UserEntity )cacheUser;
                inquiry.setExecutor(user.getCode());
                inquiry.setBoxStatus("1");
                if (StringUtils.isEmpty(inquiry.getFrequency()+"")){
                    inquiry.setFrequency(1);
                }
                inquiry.setCreateTime(new Date());
                int num = inquiryService.insertInfo(inquiry);
                return R.build(num);
            }else{
                return  R.buildError(ResultStatusEnum.TOKEN_FAILURE);
            }
        }catch (Exception e){
            e.printStackTrace();
            return  R.buildError(ResultStatusEnum.ERROR);
        }
    }
    
    /**
     * 按id查询询盘登记
     * @param id
     * @return 询盘登记实体
     */
    @RequestMapping(value = "selectByKey/{id}")
    @ResponseBody
    @ApiOperation(value = "按id查询询盘登记",notes = "按id查询询盘登记",httpMethod = "POST")
    public R<InquiryEntity> selectByKey(@PathVariable("id") Integer id){
        try {
            if (id==null){
                return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
            }
            InquiryEntity inquiry = inquiryService.selectByPrimaryKey(id);
            if (inquiry==null){
                return R.buildError(ResultStatusEnum.NOT_FOUND);
            }
            return R.build(inquiry);
        } catch (NumberFormatException e1){
            e1.printStackTrace();
            return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
        } catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 按id更新询盘登记
     * 部分字段
     * @param inquiry
     * @return 操作记录数
     */
    @RequestMapping(value = "update")
    @ResponseBody
    @ApiOperation(value = "按id更新询盘登记", notes = "按id更新询盘登记", httpMethod = "POST")
    public R<Integer> update(@RequestBody InquiryEntity inquiry){
        try {
            Object cacheUser = this.getBean("user");
            if (null!=cacheUser){
                UserEntity user = (UserEntity)cacheUser;
                inquiry.setExecutor(user.getCode());
                int num = inquiryService.updateInquiryById(inquiry);
                return R.build(num);
            }else{
                return  R.buildError(ResultStatusEnum.TOKEN_FAILURE);
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 重新询盘
     * 部分字段
     * @param inquiry
     * @return 操作记录数
     */
    @RequestMapping(value = "reInquiry")
    @ResponseBody
    @ApiOperation(value = "重新询盘", notes = "重新询盘", httpMethod = "POST")
    public R<Integer> reInquiry(@RequestBody InquiryEntity inquiry){
        try {
            int num = 0;
            Object cacheUser = this.getBean("user");
            if (null!=cacheUser){
                UserEntity user = (UserEntity )cacheUser;
                if (inquiry!=null){
                    Integer frequency = inquiry.getFrequency();
                    if (frequency>0){
                        inquiry.setFrequency(frequency+1);
                    }
                    num = inquiryService.reInquiryById(inquiry);
                }
            }else{
                return  R.buildError(ResultStatusEnum.TOKEN_FAILURE);
            }
            return R.build(num);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 按主键id删除询盘登记
     * @param id
     * @return 操作记录数
     */
    @RequestMapping(value = "delete/{id}")
    @ResponseBody
    @ApiOperation(value = "按id删除询盘登记", notes = "按id删除询盘登记", httpMethod = "POST")
    public R<Integer> delete(@PathVariable("id") Integer id){
        try {
            Object cacheUser = this.getBean("user");
            if (null!=cacheUser){
                UserEntity user = (UserEntity )cacheUser;
                InquiryEntity inquiry = inquiryService.selectByPrimaryKey(id);
                int num = 0;
                if(inquiry!=null){
                    num = inquiryService.deleteByPrimaryKey(id);
                }
                return R.build(num);
            }else{
                return  R.buildError(ResultStatusEnum.TOKEN_FAILURE);
            }
        }catch (Exception e){
            e.printStackTrace();
            return  R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 新增询盘登记产品记录
     * @param inquiryProduct
     * @return 操作记录数
     */
    @RequestMapping(value = "insertProduct" ,method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "新增询盘登记产品", notes = "新增询盘登记产品", httpMethod = "POST")
    public R<Integer> insertProduct(@RequestBody InquiryProductEntity inquiryProduct){
        try {
            Object cacheUser = this.getBean("user");
            if (null!=cacheUser){
                int num = inquiryProductService.insertSelective(inquiryProduct);
                return R.build(num);
            }else{
                return  R.buildError(ResultStatusEnum.TOKEN_FAILURE);
            }
        }catch (DataIntegrityViolationException e1){
            e1.printStackTrace();
            return R.buildError(ResultStatusEnum.DATA_ERROR);
        }catch (Exception e){
            e.printStackTrace();
            return  R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 按id查询询盘登记产品记录
     * @param id
     * @return 询盘登记产品
     */
    @RequestMapping(value = "selectProductByKey/{id}")
    @ResponseBody
    @ApiOperation(value = "按id查询询盘登记产品",notes = "按id查询询盘登记产品",httpMethod = "POST")
    public R<InquiryProductEntity> selectProductByKey(@PathVariable("id") Integer id){
        try {
            if (id==null){
                return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
            }
            InquiryProductEntity inquiryProduct = inquiryProductService.selectByPrimaryKey(id);
            if (inquiryProduct==null){
                return R.buildError(ResultStatusEnum.NOT_FOUND);
            }
            return R.build(inquiryProduct);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 按id更新询盘登记-产品
     * 部分字段
     * @param inquiryProduct
     * @return 操作记录数
     */
    @RequestMapping(value = "updateProduct")
    @ResponseBody
    @ApiOperation(value = "按id更新询盘登记产品", notes = "按id更新询盘登记产品", httpMethod = "POST")
    public R<Integer> updateProduct(@RequestBody InquiryProductEntity inquiryProduct){
        try {
            Object cacheUser = this.getBean("user");
            if (null!=cacheUser){
                int num = inquiryProductService.updateByPrimaryKeySelective(inquiryProduct);
                return R.build(num);
            }else{
                return  R.buildError(ResultStatusEnum.TOKEN_FAILURE);
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 按主键id删除询盘登记-产品
     * @param id
     * @return 操作记录数
     */
    @RequestMapping(value = "deleteProduct/{id}")
    @ResponseBody
    @ApiOperation(value = "按id删除询盘登记产品", notes = "按id删除询盘登记产品", httpMethod = "POST")
    public R<Integer> deleteProduct(@PathVariable("id") Integer id){
        try {
            Object cacheUser = this.getBean("user");
            if (null!=cacheUser){
                UserEntity user = (UserEntity )cacheUser;
                InquiryProductEntity inquiryProduct = inquiryProductService.selectByPrimaryKey(id);
                int num = 0;
                if(inquiryProduct!=null){
                    num = inquiryProductService.deleteByPrimaryKey(id);
                }
                return R.build(num);
            }else{
                return  R.buildError(ResultStatusEnum.TOKEN_FAILURE);
            }
        }catch (Exception e){
            e.printStackTrace();
            return  R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 新增询盘登记附件
     * @param inquiryFile
     * @return 操作记录数
     */
    @RequestMapping(value = "insertFile" ,method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "新增询盘登记附件", notes = "新增询盘登记附件", httpMethod = "POST")
    public R<Integer> insertFile(@RequestBody InquiryFileEntity inquiryFile){
        try {
            Object cacheUser = this.getBean("user");
            if (null!=cacheUser){
                int num = inquiryFileService.insertSelective(inquiryFile);
                return R.build(num);
            }else{
                return  R.buildError(ResultStatusEnum.TOKEN_FAILURE);
            }
        }catch (DataIntegrityViolationException e1){
            e1.printStackTrace();
            return R.buildError(ResultStatusEnum.DATA_ERROR);
        }catch (Exception e){
            e.printStackTrace();
            return  R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 按id查询询盘登记附件
     * @param id
     * @return 询盘登记附件实体
     */
    @RequestMapping(value = "selectFileByKey/{id}")
    @ResponseBody
    @ApiOperation(value = "按id查询询盘登记附件",notes = "按id查询询盘登记附件",httpMethod = "POST")
    public R<InquiryFileEntity> selectFileByKey(@PathVariable("id") Integer id){
        try {
            if (id==null){
                return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
            }
            InquiryFileEntity inquiryFile = inquiryFileService.selectByPrimaryKey(id);
            if (inquiryFile==null){
                return R.buildError(ResultStatusEnum.NOT_FOUND);
            }
            return R.build(inquiryFile);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 按id更新询盘登记-附件
     * 部分字段
     * @param inquiryFile
     * @return 操作记录数
     */
    @RequestMapping(value = "updateFile")
    @ResponseBody
    @ApiOperation(value = "按id更新询盘登记", notes = "按id更新询盘登记产品记录", httpMethod = "POST")
    public R<Integer> updateFile(@RequestBody InquiryFileEntity inquiryFile){
        try {
            Object cacheUser = this.getBean("user");
            if (null!=cacheUser){
                int num = inquiryFileService.updateByPrimaryKeySelective(inquiryFile);
                return R.build(num);
            }else{
                return  R.buildError(ResultStatusEnum.TOKEN_FAILURE);
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 按主键id删除询盘登记-附件
     * @param id
     * @return 操作记录数
     */
    @RequestMapping(value = "deleteFile/{id}")
    @ResponseBody
    @ApiOperation(value = "按id删除询盘登记附件", notes = "按id删除询盘登记附件", httpMethod = "POST")
    public R<Integer> deleteFile(@PathVariable("id") Integer id){
        try {
            Object cacheUser = this.getBean("user");
            if (null!=cacheUser){
                UserEntity user = (UserEntity )cacheUser;
                InquiryFileEntity inquiryFile = inquiryFileService.selectByPrimaryKey(id);
                int num = 0;
                if(inquiryFile!=null){
                    num = inquiryFileService.deleteByPrimaryKey(id);
                }
                return R.build(num);
            }else{
                return  R.buildError(ResultStatusEnum.TOKEN_FAILURE);
            }
        }catch (Exception e){
            e.printStackTrace();
            return  R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 新增询盘登记-历史记录
     * @param inquiryRecord
     * @return 操作记录数
     */
    @RequestMapping(value = "insertRecord" ,method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "新增询盘登记历史记录", notes = "新增询盘登记历史记录", httpMethod = "POST")
    public R<Integer> insertRecord(@RequestBody InquiryRecordEntity inquiryRecord){
        try {
            Object cacheUser = this.getBean("user");
            if (null!=cacheUser){
                int num = inquiryRecordService.insertSelective(inquiryRecord);
                return R.build(num);
            }else{
                return  R.buildError(ResultStatusEnum.TOKEN_FAILURE);
            }
        }catch (DataIntegrityViolationException e1){
            e1.printStackTrace();
            return R.buildError(ResultStatusEnum.DATA_ERROR);
        }catch (Exception e){
            e.printStackTrace();
            return  R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 按id查询询盘登记-历史记录
     * @param id
     * @return 询盘登记历史记录实体
     */
    @RequestMapping(value = "selectRecordByKey/{id}")
    @ResponseBody
    @ApiOperation(value = "按id查询询盘登记历史记录",notes = "按id查询询盘登记历史记录记录",httpMethod = "POST")
    public R<InquiryRecordEntity> selectRecordByKey(@PathVariable("id") Integer id){
        try {
            if (id==null){
                return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
            }
            InquiryRecordEntity inquiryRecord = inquiryRecordService.selectByPrimaryKey(id);
            if (inquiryRecord==null){
                return R.buildError(ResultStatusEnum.NOT_FOUND);
            }
            return R.build(inquiryRecord);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 按inId设置 询盘登记主记录
     * @param inId 询盘主键
     * @param frequency 询盘次数
     * @return
     */
    @RequestMapping(value = "setMasterRecordByInId/{inId}/{frequency}")
    @ResponseBody
    @ApiOperation(value = "按rId设置询盘登记主记录",notes = "按rId设置询盘登记主记录",httpMethod = "POST")
    public R<Boolean> setMasterRecordByRid(@PathVariable("inId") Integer inId, @PathVariable("frequency") Integer frequency){
        try {
            if (inId==null){
                return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
            }
            Boolean flag = inquiryRecordService.setMasterRecordByInId(inId,frequency);
            return R.build(flag);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }


    /**
     * 根据inId查询询盘登记 -产品
     * @param inId
     * @return 询盘登记-产品
     */
    @RequestMapping(value = "selectProductByInId/{inId}",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "根据inId查询询盘登记产品记录", notes ="根据inId查询询盘登记产品记录", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name="inId",value = "询盘登记id"),
    })
    public R<List<InquiryProductEntity>> selectProductByInId(@PathVariable("inId") Integer inId){
        try {
            if (inId==null){
                return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
            }
            List<InquiryProductEntity> list = inquiryProductService.selectProductByInId(inId);
            if (list==null){
                return R.buildError(ResultStatusEnum.SELECT_LIST_ISNULL_ERROR);
            }
            return R.build(list);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }

    }

    /**
     * 根据inId查询询盘登记-附件
     * @param inId
     * @return 询盘登记-附件
     */
    @RequestMapping(value = "selectFileByInId/{inId}",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "根据inId查询询盘登记附件", notes ="根据inId查询询盘登记附件", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name="inId",value = "询盘登记id"),
    })
    public R<List<InquiryFileEntity>> selectFileByIcId(@PathVariable("inId") Integer inId){
        try {
            if (inId==null){
                return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
            }
            List<InquiryFileEntity> list = inquiryFileService.selectFileByInId(inId);
            if (list==null){
                return R.buildError(ResultStatusEnum.SELECT_LIST_ISNULL_ERROR);
            }
            return R.build(list);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }

    }

    /**
     * 按inId查询 询盘登记 -历史记录
     * @param inId
     * @return 询盘登记 -历史记录
     */
    @RequestMapping(value = "selectRecordByInId/{inId}")
    @ResponseBody
    @ApiOperation(value = "按inId查询询盘登记历史记录",notes = "按inId查询询盘登记历史记录",httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name="inId",value = "询盘登记id"),
    })
    public R selectRecordByInId(@PathVariable("inId") Integer inId){
        try {
            if (inId==null){
                return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
            }
            Map<Integer,List<InquiryRecordEntity>> map = inquiryRecordService.selectRecordByInId(inId);
            if (map==null || map.size()==0){
                return R.buildError(ResultStatusEnum.SELECT_LIST_ISNULL_ERROR);
            }
            return R.build(map);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 按条件询盘登记
     * @param iVo
     * @return 询盘登记集合
     */
    @GetMapping("/selectInquiryListByPage")
    @ResponseBody
    public R selectInquiryListByPage(InquiryVo iVo){
        try {
            if (iVo==null){
                return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
            }
            PageInfo<InquiryEntity> pageInfo = inquiryService.selectInquiryList(iVo);
            return R.build(0,"", pageInfo.getTotal(), pageInfo.getList());
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 按id更新审核状态
     * 部分字段
     * @param iVo
     * @return 操作记录数
     */
    @RequestMapping(value = "updateBoxStatusBykey")
    @ResponseBody
    @ApiOperation(value = "按id更新审核状态", notes = "按id更新审核状态", httpMethod = "POST")
    public R<Integer> updateBoxStatusBykey(@RequestBody InquiryVo iVo){
        try {
            Object cacheUser = this.getBean("user");
            if (null!=cacheUser){
                if (null==iVo || null == iVo.getId() || null == iVo.getBoxStatus()){
                    return  R.buildError(ResultStatusEnum.PARAMETER_ERROR);
                }
                int num = inquiryService.updateBoxStatusBykey(iVo);
                return R.build(num);
            }else{
                return  R.buildError(ResultStatusEnum.TOKEN_FAILURE);
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 查询最新单号
     * @return 单号
     */
    @RequestMapping(value = "getLatestOddNumber")
    @ResponseBody
    @ApiOperation(value = "查询最新单号",notes = "查询最新单号",httpMethod = "POST")
    public R<String> selectByKey(){
        try {
            int latestOddNumberCount = inquiryService.getLatestOddNumber();
            int digit = 3;//位数
            int max = Integer.parseInt("1"+String.format("%1$0"+digit+"d",0));//右补0)
            while (latestOddNumberCount>=max){
                digit++;
                max = Integer.parseInt("1"+String.format("%1$0"+digit+"d",0));
            }
            String latestOddNumber = "";
            Date d = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String nowDateStr = sdf.format(d);
            String suffix = String.format("%0"+digit+"d", (latestOddNumberCount+1));//左补齐0
            latestOddNumber = "XP"+nowDateStr+suffix;
            return R.build(latestOddNumber);
        } catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 询盘统计-分页
     * @return
     */
    @RequestMapping("inquiryStatisticsListByPage")
    @ResponseBody
    public R inquiryStatisticsListByPage(inquiryStatisticsReq req){
        try {
            log.info("询盘统计-分页 req {}",req.toString());
            PageInfo pageInfo=inquiryService.inquiryStatisticsList(req);
            return R.build(0,"",pageInfo.getTotal(),pageInfo.getList());
        }catch (Exception e){
            log.info("询盘统计-分页 功能异常 {}",e.getMessage());
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    /**
     * 询盘统计-导出
     * @return
     */
    @RequestMapping("inquiryStatisticsExport")
    @ResponseBody
    public R inquiryStatisticsExport(inquiryStatisticsReq req){
        try {
            log.info("询盘统计-导出 req {}",req.toString());
            JSONObject obj = inquiryService.inquiryStatisticsExport(req);
            return R.build(obj);
        }catch (Exception e){
            log.info("询盘统计-导出功能异常 {}",e.getMessage());
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }


}
